/**
 * LehuOptimizer - for a faster, safer and more compatible Lehu BBS
 * @author XiaoSK
 */

// Redirect FCKeditor source path domain to the same domain as the page to post new articles
// and block useless or unavailable static files which cause long wait
chrome.webRequest.onBeforeRequest.addListener(
	function(details) {
		if(details.url == "http://my.lehu.shu.edu.cn/WebCommon/js/FCKeditor/editor/js/fckeditorcode_gecko.js") {
			// Fix FCKeditor Bug
			return {redirectUrl: "http://my.lehu.shu.edu.cn/Uploads/UserDirs/3/867/346438/file/fckeditorcode_gecko.txt"};
		} else if(details.url.indexOf("centerlogin.aspx?g=") > -1) {
			// Jump directly to BBS instead of waiting for redirection
			var c = details.url.indexOf("&urlReferrer=") + 13;
			if(details.url.substr(c, 4) == "http")
				return {redirectUrl: details.url.substr(c)};
			else
				return {redirectUrl: "http://bbs.lehu.shu.edu.cn/"};
		} else if(details.url.indexOf("WebCommon/FCKeditor/editor/images/smiley/taobao") > -1){
			// Fix smiley path error
			return {redirectUrl: details.url.replace(/FCKeditor/, "js/FCKeditor")};
		} else if(details.url == "http://bt.shu6.edu.cn/css/mobile.css") {
			// Fix img max-width
			return {redirectUrl: "data:text/css," + encodeURIComponent(".articlecontent img{max-width: 735px;}")};
		} else {
			// Block other requests
			return {cancel: true};
		}
	},
	{urls: ["http://my.lehu.shu.edu.cn/WebCommon/js/FCKeditor/editor/js/fckeditorcode_gecko.js",
		"http://my.lehu.shu.edu.cn/WebCommon/FCKeditor/editor/images/smiley/taobao/*.gif",
		"http://www.google-analytics.com/urchin.js", "http://passport.lehu.shu.edu.cn/centerlogin.aspx?g=*",
		"http://bt.shu6.edu.cn/css/mobile.css",
		"http://weibo.lehu.shu.edu.cn/*"]},
	["blocking"]
);

// Check update information
chrome.browserAction.onClicked.addListener(function() {
    chrome.tabs.create({"url": "http://xsk.tehon.org/dev/zt/LehuOptimizer/"});
});

// Fix image width overflow
chrome.tabs.onUpdated.addListener(function(tabId, changeInfo, tab) {
	if(changeInfo.status == "complete" && tab.url.indexOf("lehu.shu.edu.cn/Article.aspx?aid=") > -1) {
		chrome.tabs.executeScript(tabId, {
			code: "var p=document.querySelectorAll('.articlecontent img');for(var i in p){if(p[i].naturalWidth>735) p[i].style.maxWidth='100%';}"
		});
	}
});
